package com.example.springboot_vue.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.springboot_vue.common.CommonDto;
import com.example.springboot_vue.common.PageDto;
import com.example.springboot_vue.entity.Menu;
import com.example.springboot_vue.entity.UserEntity;
import com.example.springboot_vue.req.UserLoginReq;
import com.example.springboot_vue.resp.UserLoginResp;
import com.example.springboot_vue.service.MenuService;
import com.example.springboot_vue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @Author：sgp
 * @Package：com.example.springboot_vue.controller
 * @Project：springboot_vue
 * @name：UserController
 * @Date：2024/7/12 17:32
 * @Filename：UserController
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @PostMapping("/login")
    public CommonDto login(@RequestBody UserLoginReq req){
        CommonDto commonDto = new CommonDto<>();
        UserLoginResp loginResp = userService.login(req);
        List<Menu> byRoleId = menuService.findByRoleId(req.getRoleId());
        HashMap<Object, Object> map = new HashMap<>();
        map.put("loginResp",loginResp);
        map.put("menu",byRoleId);
        commonDto.setContent(map);
        return commonDto;
    }

    @GetMapping("/getList")
    public CommonDto getList(UserEntity userEntity) {
        CommonDto<PageDto<UserEntity>> commonDto = new CommonDto<>();
        PageDto<UserEntity> list = userService.getList(userEntity);
        commonDto.setContent(list);
        return commonDto;
    }

    @PostMapping("/saveOrUpdate")
    public CommonDto saveOrUpdate(@RequestBody UserEntity userEntity) {
        System.out.println(userEntity);
//        判断前端传过来的数据或者说就是id值，如果没有id值就是新增，否则就是修改
        CommonDto<UserEntity> commonDto = new CommonDto<>();
        if (ObjectUtils.isEmpty(userEntity.getId()) && !"null".equals(userEntity.getId())) {
            userService.save(userEntity);
            commonDto.setMessage("新增成功");
        } else {
            userService.updateById(userEntity);
            commonDto.setMessage("修改成功");
        }
        return commonDto;
    }

    @DeleteMapping("/delete/{id}")
    public CommonDto delete(@PathVariable Integer id) {
        CommonDto<UserEntity> commonDto = new CommonDto<>();
        userService.removeById(id);
        commonDto.setMessage("删除成功");
        return commonDto;
    }

    @GetMapping("/findByNo")
    public CommonDto findByNo(@RequestParam String no){
        CommonDto<UserEntity> commonDto = new CommonDto<>();
        UserEntity user= userService.findByNo(no);
        commonDto.setContent(user);
        return commonDto;
    }
}
